import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:kq_flutter_core_widget/config/kq_core_global.dart';
import 'package:kq_flutter_widgets/widgets/dialog/kq_choose_dialog.dart';
import 'package:kq_flutter_widgets/widgets/dialog/kq_confirm_dialog.dart';
import 'package:kq_flutter_widgets/widgets/dialog/kq_msg_dialog.dart';
import 'package:kq_flutter_widgets/widgets/dialog/kq_step_number_dialog.dart';
import '../resources/l10n/kq_intl.dart';
import '../widgets/dialog/kq_input_dialog.dart';
import '../widgets/dialog/kq_list_dialog.dart';
import '../widgets/dialog/kq_reason_dialog.dart';
import '../widgets/dialog/kq_custom_dialog.dart';

/// 通用对话框，简化调用过程
class KqDialog {
  ///消息对话框
  ///
  /// 顶部标题
  /// 中间内容
  /// 底部1个按钮-我知道了
  ///
  /// [msgTextAlign]：消息对齐方式，不指定则默认居中，超过一行左对齐
  static showMsgDialog(
      {String? title,
      required String msg,
      TextAlign? msgTextAlign,
      String? btnText,
      bool barrierDismissible = true,
      GestureTapCallback? onBtnTap,
      Function()? onDismiss}) {
    showDialog(
        context: KqCoreGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        barrierColor: Colors.black.withOpacity(0.2),
        builder: (context) {
          return KqMsgDialog(
            titleString: title,
            msg: msg,
            btnText: btnText ?? KqIntl.currentResource.known,
            msgTextAlign: msgTextAlign,
            onBtnTap: () {
              Navigator.pop(context);
              onBtnTap?.call();
            },
          );
        }).then((value) => onDismiss?.call());
  }

  /// 确认对话框，
  ///
  /// 顶部标题
  /// 中间内容
  /// 底部两个按钮-取消和确定
  ///
  /// [msgTextAlign]：消息对齐方式，不指定则默认居中，超过一行左对齐
  static showConfirmDialog({
    String? title,
    TextAlign? titleAlign,
    required String msg,
    Color? msgColor,
    TextAlign? msgTextAlign,
    double? msgFontSize,
    String? leftBtnText,
    String? rightBtnText,
    Color? leftBtnColor,
    Color? rightBtnColor,
    bool barrierDismissible = true,
    Color? titleColor,
    double? titleFontSize,
    FontWeight? titleFontWeight,
    double? horizontalMargin,
    GestureTapCallback? onCancel,
    GestureTapCallback? onConfirm,
    Function()? onDismiss,
    Widget Function()? msgCustomWidget,
  }) {
    showDialog(
        context: KqCoreGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        barrierColor: Colors.black.withOpacity(0.2),
        builder: (context) {
          return KqConfirmDialog(
            titleString: title,
            titleColor: titleColor,
            titleFontSize: titleFontSize,
            titleFontWeight: titleFontWeight,
            titleAlign: titleAlign,
            msg: msg,
            msgColor: msgColor,
            msgTextAlign: msgTextAlign,
            msgFontSize: msgFontSize,
            leftBtnText: leftBtnText,
            rightBtnText: rightBtnText,
            leftBtnColor: leftBtnColor,
            rightBtnColor: rightBtnColor,
            msgCustomWidget: msgCustomWidget,
            onLeftBtnTap: () {
              Navigator.pop(context);
              onCancel?.call();
            },
            onRightBtnTap: () {
              Navigator.pop(context);
              onConfirm?.call();
            },
          );
        }).then((value) => onDismiss?.call());
  }

  /// 输入对话框
  ///
  /// defValue : 默认值
  /// maxLines : 最大行数，默认1
  /// multiline : 是否支持多行，默认false
  /// allowEmpty : 内容为空是否允许确定，默认true
  /// inputTextAlign : 输入框内容对齐方式
  /// inputFormatters : 输入框内容格式限制
  /// inputType : 键盘类型
  /// autoDismissWhenTapMiddle : 是否点击中间按钮自动关闭对话框，默认true
  /// onEmptyCallback : allowEmpty = false 时，输入为空提交回调
  /// onConfirm : 确认点击回调
  static showInputDialog(String title,
      {String? subTitle,
      Color? subTitleColor,
      double? subTitleFontSize,
      String? placeHolder,
      String? defValue,
      bool multiline = false,
      bool allowEmpty = true,
      bool barrierDismissible = true,
      TextAlign? inputTextAlign,
      TextInputType? inputType,
      String? leftBtnText,
      String? rightBtnText,
      String? middleBtnText,
      int? maxCharCount,
      List<TextInputFormatter>? inputFormatters,
      bool autoDismissWhenTapLeft = true,
      bool autoDismissWhenTapRight = true,
      bool autoDismissWhenTapMiddle = true,
      bool password = false,
      bool autoSubmitWhenReturn = false,
      List<Widget>? customWidgetsBelowInput,
      Function()? onEmptyCallback, //allowEmpty = false 时，输入为空提交回调
      Function(String value)? onLeftBtnClick,
      Function(String value)? onMiddleBtnClick,
      required Function(String value) onConfirm,
      Function()? onDismiss}) {
    showDialog(
        context: KqCoreGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        barrierColor: Colors.black.withOpacity(0.2),
        builder: (context) {
          return KqInputDialog(
            defValue: defValue,
            titleString: title,
            subTitle: subTitle,
            subTitleColor: subTitleColor,
            subTitleFontSize: subTitleFontSize,
            enableClearButton: Platform.isAndroid || Platform.isIOS,
            multiline: multiline,
            placeHolder: placeHolder,
            inputType: inputType ??
                (multiline ? TextInputType.multiline : TextInputType.text),
            inputTextAlign: inputTextAlign,
            inputFormatters: inputFormatters,
            maxLines: 4,
            autoSubmitWhenReturn: Platform.isMacOS || Platform.isWindows
                ? true
                : autoSubmitWhenReturn,
            password: password,
            maxCharCount: maxCharCount,
            customWidgetsBelowInput: customWidgetsBelowInput,
            editController: TextEditingController(),
            leftBtnText: leftBtnText,
            rightBtnText: rightBtnText,
            middleBtnText: middleBtnText,
            onLeftBtnTap: (value) {
              if (onLeftBtnClick == null) {
                Navigator.pop(context);
              } else {
                if (autoDismissWhenTapLeft) {
                  Navigator.pop(context);
                }
                onLeftBtnClick.call(value);
              }
            },
            onMiddleBtnTap: (value) {
              if (autoDismissWhenTapMiddle) {
                Navigator.pop(context);
              }
              onMiddleBtnClick?.call(value);
            },
            onRightBtnTap: (value) {
              if (allowEmpty || value.isNotEmpty) {
                if (autoDismissWhenTapRight) {
                  Navigator.pop(context);
                }
                onConfirm(value);
              } else {
                if (onEmptyCallback != null) {
                  onEmptyCallback();
                }
              }
            },
          );
        }).then((value) => onDismiss?.call());
  }

  /// 列表对话框
  static showListDialog<T>(List<T> items,
      {bool barrierDismissible = true,
      String Function(int index, T item)? nameConvert,
      Function(int index, T item)? callback,
      bool searchEnable = false,
      bool Function(String searchText, T item)? onSearchItem,
      Widget? Function(int index, T item)? customItemBuilder,
      Function()? onDismiss}) {
    if (items.isEmpty) {
      return;
    }
    showDialog(
        context: KqCoreGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        barrierColor: Colors.black.withOpacity(0.2),
        builder: (context) {
          return KqListDialog(
              items: items,
              nameConvert: nameConvert,
              searchEnable: searchEnable,
              onSearchItem: onSearchItem,
              customItemBuilder: customItemBuilder,
              callback: (index, item) {
                Navigator.pop(context);
                if (callback != null) {
                  callback(index, item);
                }
              });
        }).then((value) => onDismiss?.call());
  }

  ///类似原因的对话框
  static showReasonDialog(
      {required String title,
      required String Function(int index)? renderTitleCallback,
      required int? totalCount,
      int maxRowForScroll = 6,
      String Function(int index)? renderIdCallback,
      String? chosenDataId,
      Function(int index)? callBack}) {
    return showDialog(
        barrierDismissible: true,
        context: KqCoreGlobal.globalContext,
        barrierColor: Colors.black.withOpacity(0.2),
        builder: (BuildContext context) {
          return KqReasonDialog(
            title: title,
            renderTitleCallback: renderTitleCallback,
            renderIdCallback: renderIdCallback,
            chosenDataId: chosenDataId,
            totalCount: totalCount,
            maxRowForScroll: maxRowForScroll,
            callBack: ((index) {
              Navigator.pop(context);
              if (callBack != null) {
                callBack(index);
              }
            }),
          );
        }).then((value) {});
  }

  //
  // /// 日期选择
  // static showDatePicker(
  //   BuildContext context,
  //   String title, {
  //   bool barrierDismissible = true,
  //   DateTime? minDateTime,
  //   DateTime? maxDateTime,
  //   DateTime? initialDateTime,
  //   String? leftBtnText,
  //   String? rightBtnText,
  //   bool Function(DateTime dateTime, List<int> selectedIndex)? onConfirm,
  //   Function(DateTime dateTime, List<int> selectedIndex)? onChange,
  //   Function()? onDismiss,
  //   Function()? onCancel,
  // }) {
  //   return showDialog(
  //     context: context,
  //     barrierDismissible: barrierDismissible,
  //     barrierColor: Colors.black.withOpacity(0.2),
  //     builder: (context) => KqDatePickerDialog(
  //         initialDateTime: initialDateTime ?? DateTime.now(),
  //         pickerMode: KqDateTimePickerMode.datetime,
  //         minDateTime: minDateTime,
  //         maxDateTime: maxDateTime,
  //         leftBtnText: leftBtnText,
  //         rightBtnText: rightBtnText,
  //         pickerTitleConfig: KqPickerTitleConfig(titleContent: title),
  //         dateFormat: 'yyyy年,MM月,dd日',
  //         onConfirm: onConfirm,
  //         onCancel: onCancel,
  //         onChange: onChange),
  //   ).then((value) => {onDismiss?.call()});
  // }
  //
  // /// 时间选择对话框
  // static showTimePicker(
  //   BuildContext context,
  //   String title, {
  //   bool barrierDismissible = true,
  //   DateTime? minDateTime,
  //   DateTime? maxDateTime,
  //   DateTime? initialDateTime,
  //   String? leftBtnText,
  //   String? rightBtnText,
  //   bool Function(DateTime dateTime, List<int> selectedIndex)? onConfirm,
  //   Function(DateTime dateTime, List<int> selectedIndex)? onChange,
  //   Function()? onDismiss,
  //   Function()? onCancel,
  // }) {
  //   return showDialog(
  //     context: context,
  //     barrierDismissible: barrierDismissible,
  //     barrierColor: Colors.black.withOpacity(0.2),
  //     builder: (context) => KqDatePickerDialog(
  //         initialDateTime: initialDateTime ?? DateTime.now(),
  //         pickerMode: KqDateTimePickerMode.datetime,
  //         minDateTime: minDateTime,
  //         maxDateTime: maxDateTime,
  //         leftBtnText: leftBtnText,
  //         rightBtnText: rightBtnText,
  //         pickerTitleConfig: KqPickerTitleConfig(titleContent: title),
  //         dateFormat: 'HH时:mm分:ss秒',
  //         onConfirm: onConfirm,
  //         onCancel: onCancel,
  //         onChange: onChange),
  //   ).then((value) => {onDismiss?.call()});
  // }
  //
  // /// 日期时间选择对话框
  // static showDateTimePicker(
  //   BuildContext context,
  //   String title, {
  //   bool barrierDismissible = true,
  //   bool withSecond = true,
  //   bool withMinute = true,
  //   DateTime? minDateTime,
  //   DateTime? maxDateTime,
  //   DateTime? initialDateTime,
  //   String? leftBtnText,
  //   String? rightBtnText,
  //   bool Function(DateTime dateTime, List<int> selectedIndex)? onConfirm,
  //   Function(DateTime dateTime, List<int> selectedIndex)? onChange,
  //   Function()? onDismiss,
  //   Function()? onCancel,
  // }) {
  //   return showDialog(
  //     context: context,
  //     barrierDismissible: barrierDismissible,
  //     barrierColor: Colors.black.withOpacity(0.2),
  //     builder: (context) => KqDatePickerDialog(
  //         initialDateTime: initialDateTime ?? DateTime.now(),
  //         pickerMode: KqDateTimePickerMode.datetime,
  //         minDateTime: minDateTime,
  //         maxDateTime: maxDateTime,
  //         leftBtnText: leftBtnText,
  //         rightBtnText: rightBtnText,
  //         pickerTitleConfig: KqPickerTitleConfig(titleContent: title),
  //         dateFormat:
  //             'yyyy年,MM月,dd日,HH时${withMinute ? ':mm分' : ''}${withSecond ? ':ss秒' : ''}',
  //         onConfirm: onConfirm,
  //         onCancel: onCancel,
  //         onChange: onChange),
  //   ).then((value) => {onDismiss?.call()});
  // }

  /// 显示loading
  static void showLoading({String? msg, bool showMask = false}) {
    EasyLoading.show(
        status: msg ?? KqIntl.currentResource.loading,
        maskType:
            showMask ? EasyLoadingMaskType.black : EasyLoadingMaskType.clear);
  }

  /// 关闭loading
  static void closeLoading() {
    EasyLoading.dismiss();
  }

  /// 数字步进对话框
  ///
  /// 两边加减号，中间输入框的对话框
  static showStepNumberDialog(
      {String? title,
      bool barrierDismissible = true,
      String? leftBtnText,
      String? rightBtnText,
      num min = 0,
      num? max,
      num step = 1,
      bool decimal = false,
      bool autoDismissWhenTapLeft = true,
      bool autoDismissWhenTapRight = true,
      TextEditingController? editingController,
      Function(String value)? onLeftBtnClick,
      required Function(String value) onRightBtnClick,
      Function()? onDismiss}) {
    showDialog(
        context: KqCoreGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        barrierColor: Colors.black.withOpacity(0.2),
        builder: (context) {
          return KqStepNumberDialog(
            titleString: title,
            editController: editingController ??
                TextEditingController(text: min.toString()),
            leftBtnText: leftBtnText,
            rightBtnText: rightBtnText,
            min: min,
            max: max,
            step: step,
            decimal: decimal,
            onLeftBtnTap: (value) {
              if (onLeftBtnClick == null) {
                Navigator.pop(context);
              } else {
                if (autoDismissWhenTapLeft) {
                  Navigator.pop(context);
                }
                onLeftBtnClick.call(value);
              }
            },
            onRightBtnTap: (value) {
              if (autoDismissWhenTapRight) {
                Navigator.pop(context);
              }
              onRightBtnClick(value);
            },
          );
        }).then((value) => onDismiss?.call());
  }

  // 自定义弹窗
  static showCustomDialog(
      {String? title,
      required Widget customWidget,
      Widget? Function(BuildContext context, GestureTapCallback? onCancel)?
          customBtnWidget,
      String? leftBtnText,
      String? rightBtnText,
      Color? leftBtnColor,
      Color? rightBtnColor,
      bool barrierDismissible = true,
      GestureTapCallback? onLeftTap,
      GestureTapCallback? onRightTap,
      bool isShowLeft = false,
      bool isShowRight = false,
      double? customDialogWidth,
      double? customTopPadding,
      double? customBottomPadding,
      Function()? onDismiss}) {
    showDialog(
        context: KqCoreGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        builder: (context) {
          return KqCustomDialog(
            titleString: title,
            customWidget: customWidget,
            customBtnWidget: customBtnWidget?.call(context, onLeftTap),
            leftBtnText: leftBtnText,
            //左侧灰色
            rightBtnText: rightBtnText,
            //右侧蓝色
            leftBtnColor: leftBtnColor,
            rightBtnColor: rightBtnColor,
            customDialogWidth: customDialogWidth,
            isShowLeft: isShowLeft,
            isShowRight: isShowRight,
            customTopPadding: customTopPadding,
            customBottomPadding: customBottomPadding,
            onLeftBtnTap: () {
              Navigator.pop(context);
              onLeftTap?.call();
            },
            onRightBtnTap: () {
              Navigator.pop(context);
              onRightTap?.call();
            },
          );
        }).then((value) => onDismiss?.call());
  }

  // 自定义选择框
  static showChooseDialog(
      {required String title,
      required List<KqChooseData> items,
      bool isSingleChoose = true,
      List<String>? chosenIds,
      bool barrierDismissible = true,
      Function(List<KqChooseData> chooses)? callback,
      Function()? onDismiss}) {
    showDialog(
        context: KqCoreGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        builder: (context) {
          return StatefulBuilder(builder: ((context, state) {
            return KqChooseDialog(
              title: title,
              items: items,
              state: state,
              isSingleChoose: isSingleChoose,
              chosenIds: chosenIds,
              callback: ((chooses) {
                Navigator.pop(context);
                callback?.call(chooses);
              }),
            );
          }));
        }).then((value) => onDismiss?.call());
  }
}
